import sqlalchemy as sa
from .. import perm

from .db import SqlAlchemyBase
from flask_login import UserMixin
from werkzeug.security import check_password_hash, generate_password_hash


class User(UserMixin, SqlAlchemyBase):
    __tablename__ = "users"

    id = sa.Column(
        sa.UUID(as_uuid=True),
        primary_key=True,
        server_default=sa.text("gen_random_uuid()"),
    )
    email = sa.Column(sa.String(255), nullable=False, unique=True)
    password = sa.Column(sa.String)
    perms = sa.Column(sa.Integer, default=0)

    def set_password(self, password):
        self.password = generate_password_hash(
            password,
            method="pbkdf2",
            salt_length=16,
        )

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def add_perm(self, p: int):
        perm.add(self.perms, p)

    def remove_perm(self, p: int):
        perm.remove(self.perms, p)

    def has_perm(self, p: int) -> bool:
        return perm.has(self.perms, p)
